package com.fresh.liangyi.service.impl;

import com.fresh.liangyi.dao.GoodsMapper;
import com.fresh.liangyi.model.domain.Goods;
import com.fresh.liangyi.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public int addGoods(Goods goods) {
        return goodsMapper.addGoods(goods);
    }

    @Override
    public Goods selectById(Integer id) {
        Object o = redisTemplate.opsForValue().get("goods_"+id);
        if (o != null) {
            return (Goods) o;
        } else {
            Goods goods = goodsMapper.selectById(id);
            if (goods != null) {
                redisTemplate.opsForValue().set("goods_"+id, goods, 1000, TimeUnit.SECONDS);
            }
            return goods;
        }
    }

    @Override
    public List<Goods> selectGoodsAll() {
        Object o = redisTemplate.opsForValue().get("goodsList");
        if (o != null) {
            return (List<Goods>) o;
        } else {
            List<Goods> goodsList = goodsMapper.selectGoodsAll();
            if (goodsList != null) {
                redisTemplate.opsForValue().set("goodsList", goodsList, 1, TimeUnit.SECONDS);
            }
            return goodsList;
        }
    }

    @Override
    public List<Goods> selectByKeyword(String keyword) {
        return goodsMapper.selectByKeyword(keyword);
    }

    @Override
    public List<Goods> selectByCategoryId(Integer id) {
        return selectByCategoryId(id);
    }

    @Override
    public int deleteGoods(Integer id) {
        redisTemplate.delete("goods_"+id);
        return deleteGoods(id);
    }

    @Override
    public Goods updateGoods(Goods goods) {
        goodsMapper.updateGoods(goods);
        redisTemplate.opsForValue().set("goods_"+goods.getId(),goods,1000,TimeUnit.SECONDS);
        return goods;
    }

    @Override
    public List<Goods> selectCartByUserId(Integer id) {
        return goodsMapper.selectCartByUserId(id);
    }

    @Override
    public Integer deleteCart(Integer userId, Integer goodsId) {
        return goodsMapper.deleteCart(userId,goodsId);
    }

    @Override
    public Integer addCartGoods(Integer userId, Integer goodsId) {
        return goodsMapper.addCartGoods(userId, goodsId);
    }

}
